package org.wanda.pv;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author LiuXuyang
 * Created by lxy on 2018/5/11.
 */


public class HttpClientUtil {
    public static String doPost(String url,Map<String,Object> params) throws IOException {
        //创建一个HTTPClient
        CloseableHttpClient hc=HttpClients.createDefault();
        //响应
        CloseableHttpResponse response=null;
        //存储from数据的集合
        List<NameValuePair> list=new ArrayList<>();

        UrlEncodedFormEntity from=null;
        if(params!=null){
            for (String key:params.keySet()){
                //判断value的类型
                if (params.get(key) instanceof String[]) {
                    String []values = (String[]) params.get(key);
                    for (String s: values) {
                        list.add(new BasicNameValuePair(key,s));
                    }
                }else {
                    list.add(new BasicNameValuePair(key,(String)params.get(key).toString()));
                }
            }
         from=  new UrlEncodedFormEntity(list,"utf-8");
        }
        HttpPost httpPost  =new HttpPost(url);
        httpPost.setEntity(from);
        response=hc.execute(httpPost);

        return EntityUtils.toString(response.getEntity());
    }

}
